import config from '../../config';
import { postForm } from '../../api/index';

let app = getApp();

Page({
  data: {
    imgPrefix: config.IMG_PREFIX,
    hasModal: false,
    showSuccessModal: false,
    showFailModal: false,
    submitting: false,
    form: {
      title: '',
      items: []
    }
  },

  onLoad() {
    app.getToken();
  },

  onShareAppMessage() {
    let info = wx.getStorageSync(config.USER_INFO_KEY);
    return {
      title: '吃鸡答题',
      path: '/pages/index/index?friend_id=' + info.id,
      imageUrl: config.IMG_PREFIX + '/images/share_thumb.jpeg'
    };
  },

  tapBack() {
    wx.redirectTo({
      url: '/pages/index/index'
    });
  },

  changeTitle(e) {
    this.setData({
      'form.title': e.detail.value
    });
  },

  changeItem(e) {
    let { index } = e.currentTarget.dataset;

    this.setData({
      [`form.items[${index}]`]: e.detail.value
    });
  },

  submit() {
    if (this.data.submitting) {
      return;
    }

    let formData = this.data.form;

    if (!formData.title || !formData.items[0] || !formData.items[1]) {
      this.openFailModal();
      return;
    }

    this.setData({
      submitting: true
    });

    postForm({
      data: formData,
      success: () => {
        this.openSuccessModal();
        this.setData({
          submitting: false
        });
      }
    });
  },

  openSuccessModal() {
    this.setData({
      hasModal: true,
      showSuccessModal: true
    });
  },

  closeSuccessModal() {
    this.setData({
      hasModal: false,
      showSuccessModal: false
    });
  },

  openFailModal() {
    this.setData({
      hasModal: true,
      showFailModal: true
    });
  },

  closeFailModal() {
    this.setData({
      hasModal: false,
      showFailModal: false
    });
  }
});
